package com.lqfan.autoAnswerQ.service.subject.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lqfan.autoAnswerQ.controller.importQuestions.PoiWordController;
import com.lqfan.autoAnswerQ.dao.subjectChoiceType.SubjectChoiceTypeMapper;
import com.lqfan.autoAnswerQ.model.fileType.FileType;
import com.lqfan.autoAnswerQ.model.quesBank.QuesBankModel;
import com.lqfan.autoAnswerQ.model.quesBank.Question;
import com.lqfan.autoAnswerQ.model.subject.HandleImportModel;
import com.lqfan.autoAnswerQ.model.subject.Subject;
import com.lqfan.autoAnswerQ.dao.subject.SubjectMapper;
import com.lqfan.autoAnswerQ.model.subjectChoiceType.SubjectChoiceType;
import com.lqfan.autoAnswerQ.service.fileType.IFileTypeService;
import com.lqfan.autoAnswerQ.service.quesBank.IQuestionService;
import com.lqfan.autoAnswerQ.service.subject.ISubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lqfan.autoAnswerQ.service.subjectChoiceType.ISubjectChoiceTypeService;
import com.lqfan.autoAnswerQ.service.subjectType.ISubjectTypeService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lqfan
 * @since 2020-04-04
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements ISubjectService {
    private static final Logger logger = LoggerFactory.getLogger(PoiWordController.class);

    @Autowired
    private SubjectMapper subjectMapper;
    @Autowired
    private ISubjectChoiceTypeService choiceTypeService;
    @Autowired
    private SubjectChoiceTypeMapper choiceTypeMapper;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IFileTypeService fileTypeService;
    @Autowired
    private ISubjectTypeService subjectTypeService;

    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public boolean saveHandle (ArrayList<Subject> subList, ArrayList<SubjectChoiceType> choiceList){
        //存入题目表
        logger.info("开始存入题目表");
        boolean resS = saveSubjects(subList);
        //存入选项表
        logger.info("开始存入选项表");
        boolean resC = choiceTypeService.saveChoice(choiceList);
        if(!resC || !resS){
            return false;
        }
        return true;
    }

    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public boolean saveHandle (ArrayList<HandleImportModel> handleImportModels, Question quesBank, FileType fileType){
        ArrayList<Subject> subList = new ArrayList<>();
        ArrayList<SubjectChoiceType> choiceList = new ArrayList<>();
        for (HandleImportModel importModel: handleImportModels) {
            Subject subject = new Subject();
            String sid =  importModel.getId();
            subject.setQuestionId(importModel.getQuestionId());
            subject.setId(sid);
            subject.setContent(importModel.getContent());
            subject.setTypeId(importModel.getTypeId());
            subject.setAnswer(importModel.getAnswer());

            subList.add(subject);
            choiceList = importModel.getChoiceList();
            choiceList.forEach(choiceType -> choiceType.setSubjectId(sid));
        }

        logger.info("手动导入题库: 开始存入题目表");
        boolean resS = saveSubjects(subList);
        if(!resS){
            logger.info("手动导入题库: 存入题目表失败");
            return false;
        }

        logger.info("手动导入题库: 开始存入选项表");
        boolean resC = choiceTypeService.saveChoice(choiceList);
        if(!resC){
            logger.info("手动导入题库: 存入选项表失败");
            return false;
        }
        logger.info("手动导入题库: 开始存入题库表");
        boolean resQ = questionService.save(quesBank);
        if(!resQ){
            logger.info("手动导入题库: 存入题库表失败");
            return false;
        }

        logger.info("手动导入题库: 开始存入路径表");
        boolean resF = fileTypeService.save(fileType);
        if(!resF){
            logger.info("手动导入题库: 存入路径表失败");
            return false;
        }
        return true;
    }

    @Override
    public QuesBankModel getSubjectWithPage(QuesBankModel quesBankModel, String userId, String questionId, int currentPage, int limit) {
        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("userId", userId);
        queryWrapper.eq("questionId", questionId);
        /*获取分页数据*/
        Page<Subject> page = new Page<>(currentPage,limit);
        IPage<Subject> subIPage = subjectMapper.selectPage(page, queryWrapper);
        ArrayList<Subject> list = (ArrayList<Subject>) subIPage.getRecords();

        //封装题目
        ArrayList<HandleImportModel> importModels = handleTrans(list);

        //封装选项
        for (HandleImportModel model:importModels) {
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("subjectId",model.getId());
            model.setChoiceList((ArrayList<SubjectChoiceType>) choiceTypeMapper.selectList(queryWrapper1));
        }
        quesBankModel.setHandleImportModels(importModels);
//        System.out.println(quesBankModel);
        return quesBankModel;
    }

    @Override
    public QuesBankModel getOneSubject(QuesBankModel quesBankModel, String userId, String subjectId) {
        //封装题目
        ArrayList<HandleImportModel> importModels = new ArrayList<>();

        HandleImportModel handleImportModel = new HandleImportModel();

        Subject subject = baseMapper.getSubject(subjectId);
        handleImportModel.setId(subject.getId());
        handleImportModel.setQuestionId(subject.getQuestionId());
        handleImportModel.setAnswer(subject.getAnswer());
        handleImportModel.setContent(subject.getContent());
        handleImportModel.setIsCollect(subject.getIsCollect());
        handleImportModel.setTypeId(subject.getTypeId());
        long score = subjectTypeService.getScore(subject.getTypeId());
        handleImportModel.setScore(score);

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("subjectId",subjectId);
        handleImportModel.setChoiceList((ArrayList<SubjectChoiceType>) choiceTypeMapper.selectList(queryWrapper1));
        importModels.add(handleImportModel);
        quesBankModel.setHandleImportModels(importModels);
        return quesBankModel;
    }

    @Override
    public List<Subject> getCollectSubject(String userId) {
        List<Subject> subject = baseMapper.getCollectSubject(userId);
        return subject;
    }


    @Override
    public String saveSubjects(String questionId, int typeId, String content) {
        return null;
    }

    @Transactional
    public boolean saveSubjects(ArrayList<Subject> list) {
        return batchInsert(list);
    }

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Transactional
    public boolean batchInsert(List<Subject> beanList) {
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
        SubjectMapper mapper = session.getMapper(SubjectMapper.class);
        try {
            for (int i = 0;i<beanList.size();i++) {
                mapper.insert(beanList.get(i));
                if(i%1000==999 || i==beanList.size()-1) {
                    session.commit();
                    session.clearCache();
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
            session.rollback();
            return false;
        }
        return true;
    }

    /**
     *  Subject 转化为  HandleImportModel
     */
    private ArrayList<HandleImportModel> handleTrans(ArrayList<Subject> subList) {
        ArrayList<HandleImportModel> importModels = new ArrayList<>();
        for (Subject subject : subList) {
            HandleImportModel handleImportModel = new HandleImportModel();
            handleImportModel.setId(subject.getId());
            handleImportModel.setQuestionId(subject.getQuestionId());
            handleImportModel.setAnswer(subject.getAnswer());
            handleImportModel.setContent(subject.getContent());
            handleImportModel.setIsCollect(subject.getIsCollect());
            handleImportModel.setTypeId(subject.getTypeId());
            long score = subjectTypeService.getScore(subject.getTypeId());
            handleImportModel.setScore(score);
            importModels.add(handleImportModel);
        }
        return importModels;
    }

    public int collectSub(Integer isCollect,String id,String userId){
        boolean collect  = baseMapper.collectSub(isCollect,id,userId);
        if (collect){
            return 1;
        }else {
            return 0;
        }
    }
}
